﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harkon.AppServer.cOne.Registry;

namespace Harkon.AppServer.cOne.Cluster
{
    public class ProtocolHelper
    {
        public IRegistry ServiceRegistry { get; set; }
        private string serverId = null;
        public string ServerId
        {
            get
            {
                if (serverId == null)
                    serverId = ServiceRegistry.GetRegistryUri();
                return serverId;
            }
        }
        private ASCIIEncoding encoding = new ASCIIEncoding();

        private const int TICKET_ID = 0;
        private const int TICKET_INFO = 1;

        public MulticastMessage CreateMessage(MessageType type)
        {
            switch (type)
            {
                case MessageType.Hello:
                    return new HelloIamNewMessage(ServerId);
                case MessageType.Welcome:
                    return new GreetingsFromMeMessage(ServerId);
            }
            return null;
        }

        public MulticastMessage ConvertInput(byte[] input)
        {
            string[] ticketTokens = encoding.GetString(input).Split(new char[] { '|' });

            if (ticketTokens[TICKET_ID].Equals(MessageType.Hello.ToString()))
                return new HelloIamNewMessage(ticketTokens[TICKET_INFO]);
            else if (ticketTokens[TICKET_INFO].Equals(MessageType.Hello.ToString()))
                return new GreetingsFromMeMessage(ticketTokens[TICKET_INFO]);
            return null;
        }
    }

    public enum MessageType
    {
        None,
        Hello,
        Welcome
    }

    public abstract class MulticastMessage
    {
        public string ServerId { get; set; }
        protected ASCIIEncoding encoding = new ASCIIEncoding();
        public abstract byte[] ToByteArray();

        protected string AppendServerId()
        {
            return string.Format("|{0}", ServerId);
        }

        public MulticastMessage(string serverId)
        {
            ServerId = serverId;
        }

        public override string ToString()
        {
            return string.Format("{0} - {1}", GetType().Name, ServerId);
        }
    }

    public class HelloIamNewMessage : MulticastMessage
    {
        public override byte[] ToByteArray()
        {
            return encoding.GetBytes(MessageType.Hello.ToString() + AppendServerId());
        }

        public HelloIamNewMessage(string serverId)
            : base(serverId)
        {

        }
    }

    public class GreetingsFromMeMessage : MulticastMessage
    {
        public override byte[] ToByteArray()
        {
            return encoding.GetBytes(MessageType.Welcome.ToString() + AppendServerId());
        }

        public GreetingsFromMeMessage(string serverId)
            : base(serverId)
        {

        }
    }
}
